package android.coocoo.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.coocoo.common.Const;
import android.coocoo.common.Util;
import android.coocoo.models.TaskInfo;
import android.coocoo.views.DisplayTasksListActivity;
import android.coocoo.views.R;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

/**
 * This is an example of implementing an application service that will run in
 * response to an alarm, allowing us to move long duration work out of an
 * intent receiver.
 * 
 * @see AlarmService
 * @see AlarmService_Alarm
 */
public class ReminderService extends Service {
	
	private int noOfNextTask;
	private ArrayList<TaskInfo> tasksList;
	private long timesleep;
	private ReminderThread reminderThread;
	private boolean isThreadRunning;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	public void onCreate() {
		super.onCreate();
		System.out.print("Service created");
		this.isThreadRunning = true;
		this.reminderThread = new ReminderThread();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		this.tasksList = intent.getParcelableArrayListExtra("tasksList");
		Util.reArrangeTasksList(tasksList);
		noOfNextTask = getNoOfNextTask();
		if (noOfNextTask >= 0)
			reminderThread.start();
		return START_STICKY;
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		this.isThreadRunning = false;
		this.reminderThread.interrupt();
		this.reminderThread = null;
		Log.e("reminder service", "service and thread are stopped");
	}
	
	private int getNoOfNextTask() {
		if (this.tasksList == null)
			return -1;
		else if (this.tasksList.size() == 0)
			return -1;
		int i;
		int currentYear = Calendar.getInstance().getTime().getYear();
		int currentMonth = Calendar.getInstance().getTime().getMonth();
		int currentDayOfMonth = Calendar.getInstance().getTime().getDate();
		int currentHour = Calendar.getInstance().getTime().getHours();
		int currentMinute = Calendar.getInstance().getTime().getMinutes();
		for (i=0; i<this.tasksList.size(); i++){
			Date taskDate = (Date) this.tasksList.get(i).getStartTime().clone();
			taskDate.setMinutes(taskDate.getMinutes()-this.tasksList.get(i).getBefore());
			if (currentYear <= taskDate.getYear())
				if (currentMonth <= taskDate.getMonth())
					if (currentDayOfMonth <= taskDate.getDate())
						if (currentHour <= taskDate.getHours())
							if (currentMinute <= taskDate.getMinutes())
								return i;
		}
		return -1;
	}
	
	private void notifyTask(TaskInfo taskInfo, boolean isFirstTask) {
		// TODO Auto-generated method stub
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		
		int icon = R.drawable.icon_notification;
		CharSequence tickerText = taskInfo.getTitle();
		long when = System.currentTimeMillis();

		Notification notification = new Notification(icon, tickerText, when);
		
		Context context = getApplicationContext();
		CharSequence contentTitle = "My notification";
		CharSequence contentText = "Hello World!";
		Intent notificationIntent = new Intent(this, ReminderService.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

		if (isFirstTask){
			if (taskInfo.isHasAlarm()){
				// TODO
				notification.defaults |= Notification.DEFAULT_SOUND;
				if (taskInfo.isVibration())
					notification.defaults |= Notification.DEFAULT_VIBRATE;
			}
//			notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
			
			notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		}
		
		mNotificationManager.notify(taskInfo.getId(), notification);
	}

	class ReminderThread extends Thread{
		public ReminderThread(){
			super();
		}
		
		@Override
		public void run() {
			ReminderService reminderService = ReminderService.this;
			while(reminderService.isThreadRunning){
				processTask(reminderService.tasksList, reminderService.noOfNextTask);
				try {
					if (reminderService.timesleep > 0)
						Thread.sleep(reminderService.timesleep);
					else
						Log.e("on reminderService thread", "timesleep is <= 0");
				} catch (InterruptedException e) {
					reminderService.isThreadRunning = false;
					e.printStackTrace();
				}
			}
		}

		private void processTask(ArrayList<TaskInfo> tasksList, int noOfCurrentTask) {
			if (noOfCurrentTask < 0)
				Log.e("on processTask", "noOfNextTask < 0");
			else if (tasksList == null)
				Log.e("on processTask", "tasksList is null");
			else if (tasksList.size() == 0)
				Log.e("on processTask", "tasksList size is 0");
			else if (noOfCurrentTask >= tasksList.size())
				Log.e("on processTask", "noOfNextTask >= tasksList.size()");
			else {
				TaskInfo firstTask = tasksList.get(noOfCurrentTask);
				ArrayList<TaskInfo> processedTasksList = null;
				int i;
				int noOfLastTask = noOfCurrentTask;
				for (i=noOfCurrentTask; i<tasksList.size(); i++){
					TaskInfo currentTask = tasksList.get(i);
					if (currentTask.getStartTime().getYear() == firstTask.getStartTime().getYear()
							&& currentTask.getStartTime().getMonth() == firstTask.getStartTime().getMonth()
							&& currentTask.getStartTime().getDate() == firstTask.getStartTime().getDate()
							&& currentTask.getStartTime().getHours() == firstTask.getStartTime().getHours()
							&& currentTask.getStartTime().getMinutes() == firstTask.getStartTime().getMinutes()){
						if (processedTasksList == null)
							processedTasksList = new ArrayList<TaskInfo>();
						processedTasksList.add(currentTask);
						noOfLastTask = i;
					}
				}
				if (processedTasksList != null)
					if (processedTasksList.size() > 0){
						int j;
						for (j=0; j<processedTasksList.size(); j++){
							System.out.print("Notify " + processedTasksList.get(j));
							if (j==0)
								notifyTask(processedTasksList.get(i), true);
							else notifyTask(processedTasksList.get(i), false);
						}
//						Intent intent = new Intent(getBaseContext(), AlarmBroadcastReceiver.class);
//						intent.putExtra(Const.ExtraFlag.TASKS_LIST, processedTasksList);
//						getBaseContext().sendBroadcast(intent);
					}
				if (noOfLastTask < (tasksList.size()-1)){
					noOfLastTask++;
					ReminderService.this.timesleep = (tasksList.get(noOfLastTask).getStartTime().getTime()
														- (new Date()).getTime());
				}
			}
		}
		
	}
//    NotificationManager notificationManager;
//    TaskInfo task;
//
//    @Override
//    public void onCreate() {
//    	
//        notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//
//        // show the icon in the status bar
//        showNotification();
//
//        // Start up the thread running the service.  Note that we create a
//        // separate thread because the service normally runs in the process's
//        // main thread, which we don't want to block.
//        Thread thr = new Thread(null, mTask, "ReminderService" + task.getId());
//        thr.start();
//    }
//
//    @Override
//    public void onDestroy() {
//        // Cancel the notification -- we use the same ID that we had used to start it
//        notificationManager.cancel(task.getId());
//
//        // Tell the user we stopped.
//        Toast.makeText(this, "Reminder is stopped!", Toast.LENGTH_SHORT).show();
//    }
//
//    /**
//     * The function that runs in our worker thread
//     */
//    Runnable mTask = new Runnable() {
//        public void run() {
//            // Normally we would do some work here...  for our sample, we will
//            // just sleep for 30 seconds.
//            long endTime = System.currentTimeMillis() + 15*1000;
//            while (System.currentTimeMillis() < endTime) {
//                synchronized (mBinder) {
//                    try {
//                        mBinder.wait(endTime - System.currentTimeMillis());
//                    } catch (Exception e) {
//                    }
//                }
//            }
//
//            // Done with our work...  stop the service!
//            ReminderService.this.stopSelf();
//        }
//    };
//    
//    /**
//     * This is the object that receives interactions from clients.  See RemoteService
//     * for a more complete example.
//     */
//    private final IBinder mBinder = new Binder() {
//        @Override
//                protected boolean onTransact(int code, Parcel data, Parcel reply,
//                        int flags) throws RemoteException {
//            return super.onTransact(code, data, reply, flags);
//        }
//    };
//
//    @Override
//    public IBinder onBind(Intent intent) {
//    	task = intent.getParcelableExtra("task");
//        return mBinder;
//    }
//
//    /**
//     * Show a notification while this service is running.
//     */
//    private void showNotification() {
//        // In this sample, we'll use the same text for the ticker and the expanded notification
//        CharSequence text = task.getTitle()
//        					+ "\n"
//        					+ task.getStartTime().getHours()
//        					+ ":"
//        					+ task.getStartTime().getMinutes();
//
//        // Set the icon, scrolling text and timestamp
//        Notification notification = new Notification(R.drawable.icon_notification, text,
//                System.currentTimeMillis());
//
//        // The PendingIntent to launch our activity if the user selects this notification
//        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
//                new Intent(this, DisplayTasksListActivity.class), 0);
//
//        // Set the info for the views that show in the notification panel.
//        notification.setLatestEventInfo(this, getText(R.string.alarm_service_label),
//                       text, contentIntent);
//
//        // Send the notification.
//        // We use a layout id because it is a unique number.  We use it later to cancel.
//        notificationManager.notify(task.getId(), notification);
//    }


}